package stu.kurs.security;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.security.auth.login.LoginException;

import stu.kurs.Constants;
import stu.kurs.exceptions.ServiceException;
import stu.kurs.services.IAuthorizationService;

import com.sun.appserv.security.AppservPasswordLoginModule;

public class CustomLoginModule extends AppservPasswordLoginModule {

	private IAuthorizationService authService;
	
    @SuppressWarnings("deprecation")
	@Override
    protected void authenticateUser() throws LoginException {
    	
    	
    	    	
    	if( _username == null || _password == null ) throw new LoginException( "Username of password is null" );
        if (authService == null){
        	Context ctx;
			try {
				ctx = new InitialContext();
			} catch (NamingException e) {
				throw new LoginException("Critical error");
			}
        	try {
				authService = (IAuthorizationService)ctx.lookup("java:global/y_london/AuthorizationService");
			} catch (NamingException e) {
				throw new LoginException("Critical error");
			}
        }
        Integer res = null;
        try {
			res = authService.login(_username, _password);
		} catch (ServiceException e) {
			throw new LoginException("Database error");
		}
        if (res == null ) throw new LoginException( "Bad login/password" );
        switch (res) {
		case Constants.LEVEL_USER_SIMPLE:
			commitUserAuthentication( new String[]{ "users" } );
			break;
		case Constants.LEVEL_USER_ADMIN:
			commitUserAuthentication( new String[]{ "admins" } );
			break;
		default:
			throw new LoginException( "Bad login/password" );
		}
    }
}
